//
//  收货物地址列表Ctr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/10/31.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import soapp



private var default_node = "isdefault"


public enum AddressListChange{
    case delete(NSMutableDictionary)
    case update(NSMutableDictionary)
    case add(NSMutableDictionary)
}


extension AddressListCtr{
    public class AddBar: EeBottomBar {
        let bt = UIButton()
        public override func addLayoutRules() {
            contentView.eelay = [
                [bt,[ee.T.L.B.R,[8,AppTheme.edge,-8,-AppTheme.edge]]]
            ]
            bt.ui.ntitle(title: "新增收货地址".loc).ncolor(color: ._foreground).font(size: 14).set(radius: 4, width: 1, color: ._foreground)
            backgroundColor = ._background
        }
        public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            bt.ui.ncolor(color: ._foreground).set(radius: 4, width: 1, color: ._foreground)
        }
    }
    
}

public class AddressListCtr:ListController {
    
    public var canSelected = true
    public var sections:TP.section{
        get{
            let sec = [
                [["id":"__blank"]],
                [
                    //                    ["name":__names.one_str,"phone":"186876510604","address":__titles.creat_info(5),"isDefault":"YES"],
                    //                    ["name":__names.one_str,"phone":"186876510604","address":__titles.creat_info(5)],
                    //                    ["name":__names.one_str,"phone":"186876510604","address":__titles.creat_info(5)],
                    //                    ["name":__names.one_str,"phone":"186876510604","address":__titles.creat_info(5)],
                ],
                [["id":"__blank"]],
            ]
            return sec
        }
    }
    
    public var selector:TP.selector = [
        "<section1>":ItemCell.self,
        "id<__blank>":BlankLine<line.px7>.self,
    ]
    
    public let addBt = AddBar()
    
    public var selectAddress:(NSMutableDictionary)->Void = {_ in }
    
    public var observerListChange:(AddressListChange)->Void = {_ in}
    
    public override func layTable(tableView: UIView) {
        jo_contentView.eelay = [
            [tableView,[ee.T.L.R],[addBt,ee.T,ee.B]],
            [addBt,[ee.L.B.R]],
        ]
        addBt.controller = self
        addBt.bt.addTarget(self, action: #selector(addAddress), for: .touchUpInside)
    }
    public override func viewDidLoad() {
        super.viewDidLoad()
        tableView.buildDynamicHeight(height: 80)
        tableView.separatorStyle = .none
        //        tableView.load(sections: sections, selector: selector)
        self.title = "收货地址管理".loc
        tableView.backgroundColor = UIColor.table_bg_color
        mo_request_send()
    }
    
    var addressList:NSMutableArray = NSMutableArray()
    {
        didSet{
            if addressList.count < 1
            {
                let leb = UILabel()
                leb.ui.font15.center.cl_999.text("您还没有添加过收获地址".loc)
                tableView.backgroundView = leb
            }
            else{
                let leb = UILabel()
                leb.ui.font12.text("")
                tableView.backgroundView = leb
            }
            
            
            tableView.load(sections: sections, selector: selector)
            tableView.model <-- ("section1",addressList,NodeInsert.arrayRefresh)
            tableView.reloadData()
        }
    }
    
    override public func mo_request_send() {
        loadingV.loading()
        weak var wself = self
        JoTask().get.params([PageConfig.page_size_key:100])._surl(.收货地址列表).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let list = DataNode<NSMutableArray>.path(node: "list", obj)
                {
                    wself?.addressList = list
                    return
                }
                
            }
            wself?.mo_request_alert()
        }.run()
    }
    
    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 1{
            guard let item = tableView.cellData(at: indexPath) else{
                return
            }
            if canSelected{
                self.selectAddress(item)
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    lazy var hud:HUD = {
        return HUD(at: self.mo.controller?.view)
    }()
    
    override public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        switch actionID {
        case "settingDefault":
            weak var wself = self
            hud.show().mode(.indeterminate)
            
            JoTask().post.params(["id":model["id",""]])._surl(.默认收货地址设置).json_handle { (status, msg, obj, resp) in
                wself?.hud.hide(animated: true)
                if status.isSuccess{
                    guard let ws = wself else{return}
                    
                    let list = DataNode.path(node: "section1", ws.tableView.model, value: NSMutableArray())
                    _ = list.listObj({ (dict:NSMutableDictionary) in
                        dict[default_node] = "0"
                    })
                    model[default_node] = "1"
                    ws.tableView.reloadData()
                    return
                }
                //                "默认地址设置失败".alert()
                msg.alert()
            }.run()
            
        case "deleteItem":
            let list = DataNode.path(node: "section1", tableView.model, value: NSMutableArray())
            let row = list.index(of: model)
            let ps = IndexPath(row: row, section: 1)
            
            list.remove(model)
            tableView.deleteRows(at: [ps], with: .fade)
            self.observerListChange(.delete(model))
        case "updateItem":
            self.observerListChange(.update(model))
        default:
            break
        }
    }
    
    
    @objc public func addAddress() {
        let ctr = AddressEditCtr()
        ctr.editType = .add(nil)
        weak var wself = self
        ctr.successAction = {
            _,address in
            wself?.mo_request_send()
            wself?.observerListChange(.add(address))
        }
        self.navigationController?.pushViewController(ctr, animated: true)
    }
    
    
}

extension AddressListCtr{
    public class ItemCell:JoTableCell
    {
        
        let nameL = UILabel()
        let phoneL = UILabel()
        let addressL = UILabel()
        
        let deleteBt = UIButton()
        let editBt = UIButton()
        
        let defaultBt = UIButton()
        override public func addLayoutRules() {
            contentView.eelay = [
                [nameL,[ee.L.T,[AppTheme.edge,10.+1000]]],
                [phoneL,[nameL,ee.Y],[ee.R,-AppTheme.edge]],
                [addressL,[nameL,ee.B,ee.T,8],[ee.L.R,[AppTheme.edge,-AppTheme.edge]]],
                [defaultBt,[addressL,ee.B,ee.T,6],[ee.L.B,[17,-12]]],
                [__line,[ee.L.B.R,[0,0,0]],"4"],
                [deleteBt,[ee.R,-AppTheme.edge],[defaultBt,ee.Y]],
                [editBt,[deleteBt,ee.L,ee.R,-16],[defaultBt,ee.Y]],
            ]
            
            defaultBt.contentEdgeInsets = [4,0]
            _ = nameL.ui.font15.text(color: ._foreground)
            _ = phoneL.ui.font14.text(color: ._foreground)
            _ = addressL.ui.font12.cl_888.line(2)
            __line.backgroundColor = UIColor.table_bg_color
            
            defaultBt.ui.font(size: 13).ncolor(color: ._foregroundWeak).ntitle(title: "默认地址".loc)
            defaultBt.addTarget(self, action: #selector(toggle), for: .touchUpInside)
            
            deleteBt.ui.font(size: 14).ncolor(color: ._foregroundWeak).ntitle(title: "删除".loc).actionID(ID: "delete")
            editBt.ui.font(size: 14).ncolor(color: ._foregroundWeak).ntitle(title: "修改".loc).actionID(ID: "edit")
            deleteBt.contentEdgeInsets = [6,10]
            editBt.contentEdgeInsets = [6,10]
            
            deleteBt.addTarget(self, action: #selector(actionObj(sender:)), for: .touchUpInside)
            editBt.addTarget(self, action: #selector(actionObj(sender:)), for: .touchUpInside)
        }
        
        lazy var hud:HUD = {
            return HUD(at:mo.controller?.view)
        }()
        @objc func actionObj(sender:UIButton) {
            guard let name = sender.title(for: .normal)else{return}
            if name == "修改".loc
            {
                let ctr = AddressEditCtr()
                ctr.editType = .edit(mo.model)
                weak var wself = self
                ctr.successAction = {
                    type,values in
                    wself?.mo.model["province"] = values["province",""]
                    wself?.mo.model["city"] = values["city",""]
                    wself?.mo.model["area"] = values["area",""]
                    wself?.mo.model["address"] = values["address",""]
                    wself?.mo.model["zipcode"] = values["zipcode",""]
                    wself?.mo.model["real_name"] = values["real_name",""]
                    wself?.mo.model["mobile"] = values["mobile",""]
                    wself?.mo.model["description"] = values["description",""]
                    
                    wself?.mo_model_reload()
                    wself?.active(ID: "updateItem")
                }
                mo.controller?.navigationController?.pushViewController(ctr, animated: true)
                
            }
            if name == "删除".loc{
                weak var wself = self
                JoAlertView(info:"提示".loc,"请确定是否删除该地址信息".loc,"取消".loc).append(title: "删除".loc, style: .destructive) {
                    wself?.deleteRequest()
                }.alert.show(at: mo.controller)
                
//                weak var wself = self
//                hud.show().mode(.indeterminate)
//
//                JoTask().post.log.log_response().params(["id":mo.model["id",""]])._surl(.收货地址删除).json_handle { (success, msg, obj, resp) in
//                    wself?.hud.hide(animated: true)
//                    if success{
//                        wself?.active(ID: "deleteItem")
//                        return
//                    }
//                    msg.alert()
//                }.run()
            }
        }
        
        @objc func deleteRequest() {
            weak var wself = self
            hud.show().mode(.indeterminate)
            
            JoTask().post.log.log_response().params(["id":mo.model["id",""]])._surl(.收货地址删除).json_handle { (status, msg, obj, resp) in
                wself?.hud.hide(animated: true)
                if status.isSuccess{
                    wself?.active(ID: "deleteItem")
                    return
                }
                msg.alert()
            }.run()
        }
        
        @objc func toggle() {
            if mo.model[default_node,"1"] == "0"
            {
                active(ID: "settingDefault")
            }
        }
        
        override public func mo_model_reload() {
            let address = mo.model
            
            //            let text = "Hello World"
            //            let textRange = NSMakeRange(0, text.count)
            //            let attributedText = NSMutableAttributedString(string: text)
            //            attributedText.addAttribute(NSAttributedStringKey.strikethroughStyle,
            //                                        value: NSUnderlineStyle.styleSingle.rawValue,
            //                                        range: textRange)
                nameL.text = mo.model["realname","姓名".loc]
            
            
            phoneL.text = mo.model["mobile",""].mobileDisplay()
            addressL.text = GlobalPlaceField.displayStr(address: address)
//            addressL.text = address["province",""] + address["city",""] + " " +  address["area",""] + " " + address["address",""]
            
            if mo.model[default_node,"0"] == "1"
            {
                defaultBt.setImage(UIImage(named: "radio_check_s")?.icon(18, 18, insets: .init(top: 0, left: 0, bottom: 0, right: 4)), for: .normal)
            }
            else{
                
                defaultBt.setImage(UIImage(named: "radio_check_n")?.icon(18, 18, insets: .init(top: 0, left: 0, bottom: 0, right: 4)), for: .normal)
                
            }
        }
    }
}

